package com.zrc.japktool;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Objects;

public class MainApplication extends Application {

    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("main-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 900, 600);
        stage.getIcons().add(new Image(Objects.requireNonNull(getClass().getResourceAsStream("/icons/logo.png"))));//添加icon
        stage.setTitle("JApkTool");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}

//        Test1 richEditor = new Test1();
//        BorderPane editorUI = richEditor.createRichEditorUI();
//        stage.setTitle("JavaFX 富文本编辑器（MainApplication启动）");
//        Scene scene = new Scene(editorUI, 800, 600);
//        stage.setScene(scene);
//        stage.show();

//        Test2 test2 = new Test2();
//        BorderPane test2UI = test2.createTest2UI();
//        stage.setTitle("JavaFX 日志控件测试（MainApplication启动Test2）");
//        Scene scene = new Scene(test2UI, 800, 600);
//        stage.setScene(scene);
//        stage.show();

//        Test3 test3 = new Test3();
//        BorderPane test3UI = test3.createTest3UI();
//        stage.setTitle("基于TextField的日志控件测试（MainApplication启动）");
//        Scene scene = new Scene(test3UI, 800, 600);
//        stage.setScene(scene);
//        stage.show();

//        Test4 test4 = new Test4();
//        BorderPane test3UI = test4.createTest4UI();
//        stage.setTitle("基于TextField的日志控件测试（MainApplication启动）");
//        Scene scene = new Scene(test3UI, 800, 600);
//        stage.setScene(scene);
//        stage.show();


//        Test5 test5 = new Test5();
//        BorderPane test3UI = test5.createWebLogUI();
//        stage.setTitle("基于TextField的日志控件测试（MainApplication启动）");
//        Scene scene = new Scene(test3UI, 800, 600);
//        stage.setScene(scene);
//        stage.show();












package com.zrc.japktool;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import javax.swing.*;
        import javax.swing.plaf.FontUIResource;
import java.awt.*;
        import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Objects;
import java.util.Enumeration;

public class MainApplication extends Application {
    private Stage primaryStage;
    private TrayIcon trayIcon;
    private boolean isStageVisible = false;

    // 定义强制中文逻辑字体（Java内置，跨系统支持）
    private static final Font FORCE_CHINESE_FONT = new Font("SansSerif", Font.PLAIN, 12);

    @Override
    public void start(Stage stage) throws IOException {
        this.primaryStage = stage;

        // 提前初始化AWT字体环境
        initAWTFontEnvironment();

        // 监听窗口显示/隐藏状态变化
        primaryStage.setOnShown(e -> isStageVisible = true);
        primaryStage.setOnHidden(e -> isStageVisible = false);

        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("main-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 900, 600);

        // 设置窗口图标
        stage.getIcons().add(new Image(Objects.requireNonNull(
                getClass().getResourceAsStream("/icons/logo.png"))));

        stage.setTitle("JApkTool");
        stage.setScene(scene);

        // 初始化系统托盘
        initSystemTray();

        // 拦截窗口关闭事件
        stage.setOnCloseRequest(this::handleCloseRequest);

        stage.show();
    }

    // 处理窗口关闭事件
    private void handleCloseRequest(WindowEvent event) {
        if (SystemTray.isSupported()) {
            event.consume(); // 阻止窗口真正关闭
            minimizeToTray();
        } else {
            // 不支持系统托盘时直接退出
            exitApplication();
        }
    }

    // 初始化系统托盘
    private void initSystemTray() {
        if (!SystemTray.isSupported()) {
            System.out.println("系统不支持系统托盘功能");
            return;
        }

        SystemTray systemTray = SystemTray.getSystemTray();
        java.awt.Image trayImage = null;

        // 加载托盘图标
        try {
            URL iconUrl = getClass().getResource("/icons/logo.png");
            if (iconUrl != null) {
                trayImage = Toolkit.getDefaultToolkit().createImage(iconUrl);

                // 使用MediaTracker等待图像加载完成
                MediaTracker tracker = new MediaTracker(new Panel());
                tracker.addImage(trayImage, 0);
                try {
                    tracker.waitForAll(3000);
                } catch (InterruptedException e) {
                    System.err.println("加载托盘图标时被中断: " + e.getMessage());
                    Thread.currentThread().interrupt();
                }
            } else {
                System.err.println("警告: 未找到托盘图标资源 /icons/logo.png，使用默认图标");
                BufferedImage defaultImage = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
                java.awt.Graphics g = defaultImage.getGraphics();
                g.setColor(java.awt.Color.LIGHT_GRAY);
                g.fillOval(8, 8, 16, 16);
                g.dispose();
                trayImage = defaultImage;
            }
        } catch (Exception e) {
            System.err.println("加载托盘图标失败: " + e.getMessage());
            trayImage = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
        }

        // 创建托盘菜单
        PopupMenu popupMenu = new PopupMenu();

        // 创建菜单项并显式设置字体
        MenuItem showItem = new MenuItem("显示窗口");
        showItem.setFont(FORCE_CHINESE_FONT);
        showItem.addActionListener(e -> showMainStage());

        MenuItem exitItem = new MenuItem("退出");
        exitItem.setFont(FORCE_CHINESE_FONT);
        exitItem.addActionListener(e -> exitApplication());

        popupMenu.add(showItem);
        popupMenu.addSeparator();
        popupMenu.add(exitItem);

        // 创建托盘图标
        trayIcon = new TrayIcon(trayImage, "JApkTool", popupMenu);
        trayIcon.setImageAutoSize(true);

        // 修复：添加鼠标监听器来处理双击事件
        trayIcon.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    Platform.runLater(() -> showMainStage());
                }
            }
        });

        // 添加到系统托盘
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            System.err.println("无法添加托盘图标: " + e.getMessage());
        }
    }

    // 初始化AWT字体环境
    private void initAWTFontEnvironment() {
        // 设置全局默认字体
        FontUIResource fontResource = new FontUIResource(FORCE_CHINESE_FONT);
        Enumeration<Object> keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof FontUIResource) {
                UIManager.put(key, fontResource);
            }
        }

        // 特别设置菜单相关组件的字体
        UIManager.put("MenuItem.font", fontResource);
        UIManager.put("PopupMenu.font", fontResource);
        UIManager.put("Menu.font", fontResource);
        UIManager.put("CheckBoxMenuItem.font", fontResource);
        UIManager.put("RadioButtonMenuItem.font", fontResource);

        System.out.println("全局AWT字体已强制设置为: " + FORCE_CHINESE_FONT.getName());
    }

    // 显示主窗口的统一方法
    private void showMainStage() {
        Platform.runLater(() -> {
            if (!isStageVisible) {
                primaryStage.show();
                isStageVisible = true;
            }

            // 确保窗口在最前面
            primaryStage.toFront();
            primaryStage.requestFocus();

            // 如果窗口是最小化状态，取消最小化
            if (primaryStage.isIconified()) {
                primaryStage.setIconified(false);
            }

            // 针对不同操作系统的特殊处理
            String osName = System.getProperty("os.name").toLowerCase();
            if (osName.contains("win")) {
                // Windows平台使用alwaysOnTop技巧获取焦点
                primaryStage.setAlwaysOnTop(true);
                primaryStage.setAlwaysOnTop(false);
            } else if (osName.contains("mac")) {
                // macOS平台使用反射调用私有API
                try {
                    Class<?> appClass = Class.forName("com.sun.glass.ui.Application");
                    Method getAppMethod = appClass.getMethod("GetApplication");
                    Object appInstance = getAppMethod.invoke(null);
                    Method requestForeMethod = appClass.getMethod("requestForeground", boolean.class);
                    requestForeMethod.invoke(appInstance, true);
                } catch (Exception e) {
                    System.out.println("macOS前置API调用失败，使用备选方案: " + e.getMessage());
                    primaryStage.setAlwaysOnTop(true);
                    primaryStage.setAlwaysOnTop(false);
                }
            } else if (osName.contains("linux") || osName.contains("nix")) {
                // Linux/Unix平台的处理
                primaryStage.setAlwaysOnTop(true);
                primaryStage.setAlwaysOnTop(false);
            }
        });
    }

    // 退出应用的统一方法
    private void exitApplication() {
        Platform.exit();
        if (SystemTray.isSupported() && trayIcon != null) {
            SystemTray.getSystemTray().remove(trayIcon);
        }
        System.exit(0);
    }

    // 最小化到托盘
    private void minimizeToTray() {
        primaryStage.hide();
        isStageVisible = false;
        if (trayIcon != null) {
            trayIcon.displayMessage(
                    "JApkTool",
                    "程序已最小化到系统托盘",
                    TrayIcon.MessageType.INFO
            );
        }
    }

    public static void main(String[] args) {
        // 提前设置AWT字体环境，确保在创建任何AWT组件之前
        SwingUtilities.invokeLater(() -> {
            // 在EDT线程中设置字体
            FontUIResource fontResource = new FontUIResource(FORCE_CHINESE_FONT);
            Enumeration<Object> keys = UIManager.getDefaults().keys();
            while (keys.hasMoreElements()) {
                Object key = keys.nextElement();
                Object value = UIManager.get(key);
                if (value instanceof FontUIResource) {
                    UIManager.put(key, fontResource);
                }
            }
        });

        launch(args);
    }
}